import * as vscode from 'vscode';
import * as path from 'path';
import { MavenUtils } from './mavenUtils';

export class MavenTerminal {
    private mavenUtils: MavenUtils;
    
    constructor() {
        this.mavenUtils = new MavenUtils();
    }
    
    /**
     * 在当前Maven模块路径打开终端
     */
    public async openTerminalAtModule(): Promise<void> {
        const editor = vscode.window.activeTextEditor;
        let modulePath: string | undefined;
        
        // 如果当前编辑器打开的是POM文件
        if (editor && editor.document.fileName.endsWith('pom.xml')) {
            modulePath = path.dirname(editor.document.fileName);
        } else {
            // 否则让用户选择一个Maven模块
            const pomFiles = await this.mavenUtils.findAllPomFiles();
            if (pomFiles.length === 0) {
                vscode.window.showErrorMessage('找不到POM文件');
                return;
            }
            
            if (pomFiles.length === 1) {
                modulePath = path.dirname(pomFiles[0].fsPath);
            } else {
                const selectedPom = await vscode.window.showQuickPick(
                    pomFiles.map(file => ({
                        label: path.basename(path.dirname(file.fsPath)),
                        description: path.dirname(file.fsPath)
                    })),
                    { placeHolder: '选择要打开终端的Maven模块' }
                );
                
                if (selectedPom) {
                    modulePath = selectedPom.description;
                } else {
                    return;
                }
            }
        }
        
        if (modulePath) {
            // 创建终端并在模块路径打开
            const terminal = vscode.window.createTerminal(`Maven: ${path.basename(modulePath)}`);
            terminal.sendText(`cd "${modulePath}"`);
            
            // 显示Maven版本信息，确认终端正常工作
            const mvn = await this.mavenUtils.getMavenExecutable();
            terminal.sendText(`${mvn} --version`);
            terminal.show();
        }
    }
}
